package co.yixiang.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Path;
import java.util.HashMap;

public class QRCodeGenerator {
    private static final Logger log= LoggerFactory.getLogger(QRCodeGenerator.class);
    /**
     * 生成二维码
     * @param contents 二维码内容
     * @param path   生成二维码存储地址
     */
    public static void generateCode(String contents, String path) {
        int width = 340;
        int height = 340;
        String format = "jpg";
        HashMap map = new HashMap();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 0);
        try {
            BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,map);
            Path file = new File(path).toPath();
            MatrixToImageWriter.writeToPath(bm, format, file);
        } catch (WriterException e) {
            log.info("生成二维码异常",e);
        } catch (IOException e) {
            log.info("把二维码写入指定位置异常",e);
        }
    }
    /**
     * 将文件转换成byte数组
     * @param filePath
     * @return
     */
    public static byte[] File2byte(File filePath){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            log.info("文件不存在",e);
        }catch (IOException e){
            log.info("文件读取异常",e);
        }
        return buffer;
    }


    public static void main(String[] args) {
        generateCode("https://mbas.mbs.boc.cn/WeiBankFront/weixinVue/etc/index.html#/index?channelId=B441234567890","d:\\code.jpg");
    }

}
